package com.boyi.shared.util;

/**
 * 字节转换
 *
 * @author 颜培轩
 * @date 2018年07月10日  上午 10:41
 */
public class ByteConvert {
	/**
	 * created at 2017/5/25 21:15
	 * int转byte
	 */
	public static byte intToByte(int x) {
		return (byte) x;
	}

	/**
	 * created at 2017/5/25 21:15
	 * byte转int
	 */
	public static int byteToInt(byte b) {
		return b & 0xFF;
	}

	/**
	 * created at 2017/5/25 21:14
	 * 判断一个数是否为整数，是返回true，
	 */
	public static boolean isNumeric(String s) {
		if (s != null && !"".equals(s.trim()))
			return s.matches("^[0-9]*$");
		else
			return false;
	}

	/**
	 * created at 2017/5/25 21:16
	 * byte数组转String16进制输出
	 */
	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = String.format("%02x", v);
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	public static byte[] HexStringToBytes(String[] codes) {
		int[] a = new int[codes.length];
		for (int i = 0, k = codes.length; i < k; i++) {
			a[i] = Integer.valueOf(codes[i], 16);
		}
		int[] intsCRC = CRC16.getCrc16(a);

		byte[] bytes = new byte[intsCRC.length];
		for (int i = 0; i < intsCRC.length; i++) {
			byte b1 = ByteConvert.intToByte(intsCRC[i]);
			bytes[i] = b1;
		}
		return bytes;
	}

	/**
	 * created at 2017/5/25 21:18
	 * byte转String16进制输出
	 */
	public static String byteToHexString(byte src) {
		StringBuilder stringBuilder = new StringBuilder("");
		int v = src & 0xFF;
		String hv = Integer.toHexString(v);
		if (hv.length() < 2) {
			stringBuilder.append(0);
		}
		stringBuilder.append(hv);
		return stringBuilder.toString();
	}

	/**
	 * 将整型数字转换为二进制字符串，一共32位，不舍弃前面的0
	 *
	 * @param number 整型数字
	 * @return 二进制字符串
	 */
	public static String get32BitBinString(int number) {
		StringBuilder sBuilder = new StringBuilder();
		for (int i = 0; i < 32; i++) {
			sBuilder.append(number & 1);
			number = number >>> 1;
		}
		return sBuilder.reverse().toString();
	}

	/**
	 * 将整型数字转换为二进制字符串，舍弃前面的0
	 *
	 * @param number 整型数字
	 * @return 二进制字符串
	 */
	public static String getSimpleBinString(int number) {
		StringBuilder sBuilder = new StringBuilder();
		for (int i = 0; i < 32; i++) {
			sBuilder.append(number & 1);
			number = number >>> 1;
		}
		int index = sBuilder.reverse().indexOf("1");
		return sBuilder.substring(index);
	}
}
